﻿using DotNetty.Buffers;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;
using Raspberry.Printer.Sockets.Client;
using Raspberry.Printer.Sockets.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Raspberry.Printer.Sockets.HandlerAdapter
{
    /// <summary>
    /// 一个缺省的服务器处理对象，只提供处理IByteBuffer的能力
    /// </summary>
    /// <typeparam name="TContext"></typeparam>
    public class DefaultClientHandler : ChannelHandlerAdapter, UserToken
    {
        /// <summary>
        /// 构建一个缺省的服务器处理对象
        /// </summary>
        /// <param name="socketServer"></param>
        /// <param name="context"></param>
        public DefaultClientHandler(SocketClient socketServer)
        {
            ClientInstance = socketServer;

        }

        public override void ChannelActive(IChannelHandlerContext context)
        {
            ChannelContext = context;
            base.ChannelActive(context);
            Console.WriteLine("我是客户端.");
        }

        public override async void ChannelRead(IChannelHandlerContext context, object message)
        {
            await Task.Run(() =>
            {
                var buffer = message as Byte [];
                if (buffer != null)
                {
                    ClientInstance.OnReceivePackage(this, buffer);
                }
            });
        }

        public override async void ChannelReadComplete(IChannelHandlerContext context)
        {
            await Task.Run(() => { context.Flush(); });
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            ClientInstance.OnErrord(this, exception.Message, exception);
            context.CloseAsync();
        }

        public override void HandlerAdded(IChannelHandlerContext context)
        {
            base.HandlerAdded(context);
            //this.ChannelContext = context;
            // IPAddress = context.Channel.RemoteAddress.ToString();
            ConnectTime = DateTime.Now;
            ClientInstance.OnConnect(this);

        }

        public override void HandlerRemoved(IChannelHandlerContext context)
        {
            ClientInstance.OnClosed(this);
            base.HandlerRemoved(context);
            ChannelContext = null;
        }

        public override async void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("已经15秒未收到客户端的消息了！");
                if (evt is IdleStateEvent eventState)
                {
                    if (eventState.State == IdleState.ReaderIdle)
                    {
                        Console.WriteLine("关闭这个不活跃通道！");
                        context.CloseAsync();
                    }
                }
                else
                {
                    base.UserEventTriggered(context, evt);
                }
            });
        }

        public async void Send(Byte [] data)
        {
            if (ChannelContext != null)
            {
                await ChannelContext?.WriteAndFlushAsync(data);
            }

        }


        public Boolean Connected
        {
            get
            {
                return ChannelContext != null;
            }
        }


        /// <summary>
        /// 服务实例
        /// </summary>
        private SocketClient ClientInstance;

        /// <summary>
        /// 通道上下文，发送数据用
        /// </summary>
        private IChannelHandlerContext ChannelContext;

        public Object UserData { get; set; }

        public string IPAddress { get; protected set; }

        public DateTime ConnectTime { get; protected set; }

    }
}
